package pl.edu.agh.io.fx3.saver;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import pl.edu.agh.io.fx3.filesystem.FileSystemFactory;

/**
 * Creates new session if specified doesn't exists.
 * @author Konrad Tendera
 *
 */
public class MyBatisConnectionFactory {

	private static SqlSessionFactory sqlSessionFactory;

	static {
		try {
			String resource = "mybatis-config.xml";
			Reader reader = Resources.getResourceAsReader(resource);

			if (sqlSessionFactory == null) {
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			}
		}
		catch (FileNotFoundException fileNotFoundException) {
			FileSystemFactory.LOGGER.error(fileNotFoundException);
			fileNotFoundException.printStackTrace();
		} catch (IOException iOException) {
			FileSystemFactory.LOGGER.error(iOException);
			iOException.printStackTrace();
		}
		FileSystemFactory.LOGGER.info("New instance of SqlSessionFactory created");
	}

	/**
	 * Returns existing {@link SqlSessionFactory} instance or creates new one if doesn't exist yet.
	 * @return {@link SqlSessionFactory} instance.
	 */
	public static SqlSessionFactory getSqlSessionFactory() {
		FileSystemFactory.LOGGER.debug("Obtaining SqlSessionFactory instance");
		return sqlSessionFactory;
	}

}
